import sys
from collections import defaultdict
from datetime import datetime, date

num_items = 6095

def write_features(ofile, f):
    desc = ' '.join(map(lambda (fid, v): '%d:%.3f' % (fid, v), f))
    ofile.write('%d %s\n' % (len(f), desc))

if __name__ == '__main__':
    if len(sys.argv) < 3:
        print 'usage: <train> <features> [-w2|-h3|-w7]'
        sys.exit(1)
    
    num_features={'-w2': 2, '-h3': 3, '-w7': 7, '-h24': 24, '-h24w2': 48}

    option = '-w2'
    if len(sys.argv) >= 4:
        assert sys.argv[3] in num_features, sys.argv[3]
        option = sys.argv[3]

    mul_items = False
    if len(sys.argv) >= 5:
        assert sys.argv[4] == '-items'
        mul_items = True

    ofile = open(sys.argv[2], "w")
    r = num_items if mul_items else 1 
    ofile.write('%d\n' % (num_features[option] * r))
    num_f = num_features[option]

    for line in open(sys.argv[1]):
        uid, iid, rt, t = map(int, line.split())

        dt = datetime.fromtimestamp(t)
        f = []

        if option == '-w2':
            wd = dt.weekday()
            fid = 1 if wd == 0 or wd == 6 else 0
            f.append([fid, 1])
        elif option == '-h3':
            h = dt.hour
            f.append([h / 8, 1])
        elif option == '-h24':
            h = dt.hour
            f.append([h, 1])
        elif option == '-w7':
            wd = dt.weekday()
            f.append([wd, 1])
        elif option == '-h24w2':
            wd = dt.weekday()
            h = dt.hour
            f.append([24*(wd == 0 or wd == 6) + h, 1])

        if mul_items:
            f = map(lambda (x, v): (x+iid*num_f, v), f)
        write_features(ofile, f)

    ofile.close()
